<template>
    <div class="staff-management">
        <div class="head">
            <el-form :model="queryParams" ref="queryForm" :inline="true">
                <el-form-item label="员工姓名" prop="staffName">
                    <el-input v-model="queryParams.staffName" placeholder="请输入员工姓名" clearable style="width: 240px" />
                </el-form-item>

                <el-form-item label="员工状态" prop="staffStatus">
                    <el-select v-model="queryParams.staffStatus" placeholder="请选择员工状态" filterable>
                        <el-option label="在职" value="1"></el-option>
                        <el-option label="离职" value="0"></el-option>
                    </el-select>
                </el-form-item>
                
                <el-form-item label="所属部门" prop="departmentId">
                    <el-select v-model="queryParams.departmentId" placeholder="请选择部门" filterable>
                        <el-option v-for="item in departmentList" :label="item.departmentName" :key="item.departmentId"
                            :value="item.departmentId"></el-option>
                    </el-select>
                </el-form-item>

                <el-form-item>
                    <el-button type="primary" size="default" @click="searchBtn()">搜索</el-button>
                    <el-button size="default" @click="resetBtn">重置</el-button>
                </el-form-item>
            </el-form>

            <div class="middle">
                <div class="add" style="margin-left: 20px;">
                    <div class="button">
                        <el-button type="primary" :icon="Plus" @click="handleAdd()" plain>新增</el-button>
                    </div>
                </div>
                <div class=" add">
                    <div class="button">
                        <el-button type="success" :icon="Edit" @click="handleEdit()" :disabled="single"
                            plain>修改</el-button>
                    </div>
                </div>
                <div class=" add">
                    <div class="button">
                        <el-button type="danger" :icon="Delete" @click="handleDelete()" :disabled="multiple" plain>
                            删除
                        </el-button>
                    </div>
                </div>
            </div>
            
            <div class="end">
                <el-table :data="tableData" row-key="staffId" style="width: 100%"
                    @selection-change="handleSelectionChange">
                    <el-table-column type="selection" />
                    <el-table-column label="序号" prop="index">
                        <template #default="scope">{{ scope.$index + 1 }}</template>
                    </el-table-column>
                    <el-table-column property="staffName" label="员工姓名" />
                    <el-table-column property="staffNumber" label="工号" />
                    <el-table-column property="departmentName" label="所属部门" />
                    <el-table-column property="position" label="职位" />
                    <el-table-column property="phone" label="联系电话" />
                    <el-table-column property="email" label="邮箱" />
                    <el-table-column property="hireDate" label="入职日期" />
                    <el-table-column label="状态">
                        <template #default="scope">
                            <el-button type="success" v-if="scope.row.staffStatus == 1" plain>在职</el-button>
                            <el-button type="warning" v-else plain>离职</el-button>
                        </template>
                    </el-table-column>
                    <el-table-column label="操作">
                        <template #default="scope">
                            <el-button size="small" @click="handleEdit(scope.row)">
                                修改
                            </el-button>
                            <br>
                            <el-button size="small" type="danger" @click="handleDelete(scope.row)">
                                删除
                            </el-button>
                        </template>
                    </el-table-column>
                </el-table>
                <div style="margin-left: 600px;">
                    <div class="demo-pagination-block">
                        <el-pagination v-model:current-page="queryParams.pageNum"
                            v-model:page-size="queryParams.pageSize" :page-sizes="[10, 20, 50, 100]"
                            layout="total, sizes, prev, pager, next, jumper" :total="total"
                            @size-change="handleSizeChange" @current-change="handleCurrentChange" />
                    </div>
                </div>
            </div>

            <el-dialog v-model="dialogVisible" :modal="true" width="800px">
                <el-form :model="formData" :rules="rules" ref="staffForm">
                    <el-row>
                        <el-col :span="11">
                            <el-form-item label="员工姓名" label-width="120px" prop="staffName">
                                <el-input v-model="formData.staffName" autocomplete="off"></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="11">
                            <el-form-item label="工号" label-width="120px" prop="staffNumber">
                                <el-input v-model="formData.staffNumber" autocomplete="off" :disabled="disabled"></el-input>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    
                    <el-row>
                        <el-col :span="11">
                            <el-form-item label="所属部门" label-width="120px" prop="departmentId">
                                <el-select v-model="formData.departmentId" placeholder="请选择部门" 
                                    filterable required>
                                    <el-option v-for="item in departmentList" :label="item.departmentName"
                                        :key="item.departmentId" :value="item.departmentId"></el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="11">
                            <el-form-item label="职位" label-width="120px" prop="position">
                                <el-input v-model="formData.position" autocomplete="off"></el-input>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    
                    <el-row>
                        <el-col :span="11">
                            <el-form-item label="联系电话" label-width="120px" prop="phone">
                                <el-input v-model="formData.phone" autocomplete="off"></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="11">
                            <el-form-item label="邮箱" label-width="120px" prop="email">
                                <el-input v-model="formData.email" autocomplete="off"></el-input>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    
                    <el-row>
                        <el-col :span="11">
                            <el-form-item label="入职日期" label-width="120px" prop="hireDate">
                                <el-date-picker v-model="formData.hireDate" type="date" 
                                    value-format="YYYY-MM-DD" placeholder="选择日期">
                                </el-date-picker>
                            </el-form-item>
                        </el-col>
                        <el-col :span="11">
                            <el-form-item label="状态" label-width="120px" prop="staffStatus">
                                <el-select v-model="formData.staffStatus" placeholder="请选择状态">
                                    <el-option label="在职" value="1"></el-option>
                                    <el-option label="离职" value="0"></el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    
                    <el-row>
                        <el-col :span="22">
                            <el-form-item label="备注" label-width="120px" prop="remark">
                                <el-input v-model="formData.remark" type="textarea" autocomplete="off"></el-input>
                            </el-form-item>
                        </el-col>
                    </el-row>
                </el-form>
                <template #footer>
                    <div class="dialog-footer">
                        <el-button @click="handleCanle">取消</el-button>
                        <el-button type="primary" @click="handleConfirm">
                            确认
                        </el-button>
                    </div>
                </template>
            </el-dialog>

            <el-dialog v-model="deleteDialog" title="提示" width="500">
                <span>确认要删除选中的员工吗？</span>
                <template #footer>
                    <div class="dialog-footer">
                        <el-button @click="deleteDialog = false">取消</el-button>
                        <el-button type="primary" @click="deleteConfirm">
                            确定
                        </el-button>
                    </div>
                </template>
            </el-dialog>
        </div>
    </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { Calendar, Search, Edit, Plus, Delete } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { 
    selectAllStaff, 
    selectAllDepartments, 
    addStaff, 
    getStaff, 
    updateStaff, 
    deleteStaff 
} from '@/api/staff'

const staffForm = ref(null);
const single = ref(true)
const multiple = ref(true)
const total = ref(0);
const dialogVisible = ref(false)
const selected = ref("add");
const disabled = ref(false)
const selectRow = ref([]);
const deleteDialog = ref(false)
const deleteRow = ref([])
const departmentList = ref([])

onMounted(async () => {
    await getDepartmentList();
    await getStaffList();
})

// 查询参数
const queryParams = ref({
    staffId: '',
    staffName: '',
    staffStatus: '',
    departmentId: '',
    pageNum: 1,
    pageSize: 10
})

// 表单参数
const formData = ref({
    staffId: '',
    staffName: '',
    staffNumber: '',
    departmentId: '',
    position: '',
    phone: '',
    email: '',
    hireDate: '',
    staffStatus: '1',
    remark: ''
})

// 表格数据
const tableData = ref([])

// 校验规则
const rules = {
    staffName: [
        { required: true, message: '请输入员工姓名', trigger: 'blur' }
    ],
    staffNumber: [
        { required: true, message: '请输入工号', trigger: 'blur' }
    ],
    departmentId: [
        { required: true, message: '请选择部门', trigger: 'change' }
    ],
    position: [
        { required: true, message: '请输入职位', trigger: 'blur' }
    ],
    phone: [
        { required: true, message: '请输入联系电话', trigger: 'blur' },
        {
            pattern: /^1[3-9]\d{9}$/,
            message: '请输入正确的手机号码',
            trigger: 'blur'
        }
    ],
    email: [
        { required: true, message: '请输入邮箱', trigger: 'blur' },
        {
            type: 'email',
            message: '请输入正确的邮箱地址',
            trigger: ['blur', 'change']
        }
    ],
    hireDate: [
        { required: true, message: '请选择入职日期', trigger: 'change' }
    ],
    staffStatus: [
        { required: true, message: '请选择状态', trigger: 'change' }
    ]
}

// 修改
function handleEdit(row) {
    resetForm();
    if (row == null) {
        row = selectRow.value[0];
    }
    disabled.value = true
    selected.value = 'edit'
    const data = {
        staffId: row.staffId
    }
    getStaff(data).then(res => {
        formData.value = res.data.staff;
        dialogVisible.value = true
    })
}

// 删除
function handleDelete(row) {
    if (row == null) {
        row = selectRow.value.map(item => {
            return item.staffId
        })
    } else {
        row = [row.staffId]
    }
    deleteRow.value = row
    deleteDialog.value = true;
}

// 删除确认
function deleteConfirm() {
    deleteStaff(deleteRow.value).then(res => {
        if (res.code === 500) {
            ElMessage.error(res.message);
        } else {
            ElMessage.success("删除成功")
        }
        getStaffList();
    })
    deleteDialog.value = false;
}

// 新增
function handleAdd() {
    dialogVisible.value = true
    selected.value = 'add'
    resetForm();
}

// 每页条数变化
function handleSizeChange(val) {
    queryParams.value.pageSize = val;
    queryParams.value.pageNum = 1;
    getStaffList();
}

// 页码变化
function handleCurrentChange(val) {
    queryParams.value.pageNum = val;
    getStaffList();
}

// 关闭dialog
function handleCanle() {
    dialogVisible.value = false
    staffForm.value.resetFields();
    staffForm.value.clearValidate();
}

// 选中行
function handleSelectionChange(selected) {
    single.value = selected.length != 1
    multiple.value = selected.length == 0
    selectRow.value = selected;
}

// 确认提交
function handleConfirm() {
    staffForm.value.validate((valid) => {
        if (valid) {
            if (selected.value === 'add') {
                addStaff(formData.value).then(res => {
                    if (res.code === 500) {
                        ElMessage.error(res.message);
                    } else {
                        ElMessage.success("新增成功")
                    }
                    getStaffList();
                    dialogVisible.value = false
                })
            } else {
                updateStaff(formData.value).then(res => {
                    if (res.code === 500) {
                        ElMessage.error(res.message);
                    } else {
                        ElMessage.success("修改成功")
                    }
                    getStaffList();
                    dialogVisible.value = false
                })
            }
        } else {
            ElMessage.warning("请填写完整")
        }
    });
    staffForm.value.clearValidate();
}

// 搜索
function searchBtn() {
    queryParams.value.pageNum = 1;
    getStaffList()
}

// 重置
function resetBtn() {
    queryParams.value = {
        staffId: '',
        staffName: '',
        staffStatus: '',
        departmentId: '',
        pageNum: 1,
        pageSize: queryParams.value.pageSize
    }
    getStaffList()
}

// 重置表单
function resetForm() {
    formData.value = {
        staffId: '',
        staffName: '',
        staffNumber: '',
        departmentId: '',
        position: '',
        phone: '',
        email: '',
        hireDate: '',
        staffStatus: '1',
        remark: ''
    }
    disabled.value = false
    selected.value = 'add'
}

// 获取员工列表
async function getStaffList() {
    try {
        const res = await selectAllStaff(queryParams.value);
        total.value = res.data.total
        tableData.value = res.data.list
        // 关联部门名称
        for (const item of tableData.value) {
            for (const dept of departmentList.value) {
                if (dept.departmentId == item.departmentId) {
                    item.departmentName = dept.departmentName
                }
            }
        }
    } catch (error) {
        console.log(error)
    }
}

// 获取部门列表
async function getDepartmentList() {
    try {
        const res = await selectAllDepartments();
        departmentList.value = res.data.departmentList
    } catch (e) {
        console.log(e)
    }
}
</script>

<style scoped>
.staff-management {
    height: 100%;
    width: calc(100% - 50px);
    float: left;
}

.head {
    margin-top: 20px;
    margin-left: 20px;
    width: calc(100% - 50px);
}

.middle {
    width: 100%;
    height: 8vh;
    margin-bottom: 20px;
}

.add {
    margin-top: 15px;
    margin-left: 45px;
    width: 5%;
    height: 50%;
    float: left;
}

.end {
    float: left;
    width: calc(100% - 50px);
}
</style>